package com.eriloan.easyPage.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.eriloan.easyPage.beans.ModelAttribute;
import com.eriloan.easyPage.util.EasyPageContext;
import com.eriloan.easyPage.util.EasyPageTools;

/**
 * 
 * <p>Copyright: All Rights Reserved</p>
 * <p>Company: 北京荣之联科技股份有限公司 http://www.ronglian.com</p>
 * <p>Description: View 层 控制类</p>
 * <p>Author:Eric Shi/史丙利</p>
 */
public class EasyPageController{

	public final Logger log = Logger.getLogger(this.getClass().getName());

	/**
	 * 模板类型--velocity
	 */
	public static final String TEMPLATE_TYPE_VELOCITY = "velocity";
	/**
	 * 模板类型--freemarker
	 */
	public static final String TEMPLATE_TYPE_FREEMARKER = "freemarker";

	public EasyPageController(){

	}

	/**
	 * 
	 * <br/>Description:以json形式返回结果--文本
	 * <p>Author:Eric Shi/史丙利</p>
	 * 
	 * @param obj
	 * @return
	 */
	protected final String Result_JsonTxt(Object obj){
		try{
			EasyPageContext easyPageContext = new EasyPageContext();
			HttpServletResponse response = easyPageContext.getResponse();
			response.setContentType("text/html;charset=" + easyPageContext.getCharset());
			PrintWriter out = response.getWriter();
			com.google.gson.Gson gson = new com.google.gson.Gson();
			String s = gson.toJson(obj).toString();
			out.println(s.toString());
			out.close();
		}catch(IOException e){
			e.printStackTrace();
		}

		return obj.toString();
	}

	/**
	 * 
	 * <br/>Description:以json形式返回结果--文件
	 * <p>Author:Eric Shi/史丙利</p>
	 * 
	 * @param obj
	 * @return
	 */
	protected final String Result_JsonFile(Object obj){
		try{
			EasyPageContext easyPageContext = new EasyPageContext();
			HttpServletResponse response = easyPageContext.getResponse();
			response.setContentType("application/x-json; charset=" + easyPageContext.getCharset());
			PrintWriter out = response.getWriter();
			com.google.gson.Gson gson = new com.google.gson.Gson();
			String s = gson.toJson(obj).toString();
			out.println(s.toString());
			out.close();
		}catch(IOException e){
			e.printStackTrace();
		}

		return obj.toString();
	}

	/**
	 * 
	 * <br/>Description:跳转到页面--无参方式
	 * <p>Author:Eric Shi/史丙利</p>
	 * 
	 * @param val
	 * @return
	 */
	protected final String ForwardPage(String pathName){
		EasyPageContext easyPageContext = new EasyPageContext();
		try{
			HttpServletRequest req = easyPageContext.getRequest();
			HttpServletResponse res = easyPageContext.getResponse();
			req.getRequestDispatcher("/" + pathName + easyPageContext.getPageSuffix()).forward(req,res);
		}catch(IOException e){
			e.printStackTrace();
		}catch(ServletException e){
			e.printStackTrace();
		}
		return pathName;
	}

	/**
	 * 
	 * <br/>Description:跳转到页面--有参方式
	 * <p>Author:Eric Shi/史丙利</p>
	 * 
	 * @param mapAttributes
	 * @param pathName
	 * @return
	 */
	protected final String ForwardPage(ModelAttribute modelAttribute,String pathName){
		EasyPageContext easyPageContext = new EasyPageContext();

		HttpServletRequest req = easyPageContext.getRequest();
		HttpServletResponse res = easyPageContext.getResponse();

		Map<String,Object> ma = modelAttribute.getModelAttributes();
		Map<String,Object> msa = modelAttribute.getModelSessionAttributes();
		Map<String,Object> mca = modelAttribute.getModelCookieAttributes();

		// session attribute
		if(null != msa && msa.size() != 0){
			for(Map.Entry<String,Object> m:msa.entrySet()){
				easyPageContext.getSession().setAttribute(m.getKey(),m.getValue());
			}
		}

		// cookie attribute
		if(null != mca && mca.size() != 0){
			for(Map.Entry<String,Object> m:mca.entrySet()){
				EasyPageTools.addCookie(easyPageContext.getResponse(),m.getKey(),m.getValue().toString());
			}
		}

		try{
			if(EasyPageTools.isAjaxRequest(easyPageContext.getRequest())){
				if(null != ma && ma.size() != 0){
					// this.Result_JsonTxt(modelAttribute.getModelAttributes());
					this.Result_JsonFile(modelAttribute.getModelAttributes());
				}
			}else{
				if(EasyPageContext.threadLocalIsTemplateView.get()){

					if(EasyPageController.TEMPLATE_TYPE_VELOCITY.equalsIgnoreCase(EasyPageContext.threadLocalTemplateType.get())){
						Class<?> templateClass = EasyPageTools.getClassByClassForName("com.eriloan.easyPage.plugins.templates.velocity.VelocityPluginsManagement");

						Method vm = null;

						Method[] vmds = templateClass.getMethods();

						for(Method m:vmds){
							if("getVelocityTemplate".equals(m.getName())){
								vm = m;
								break;
							}
						}

						Object[] sobjs = {easyPageContext,ma,pathName + easyPageContext.getPageSuffix()};

						vm.invoke(templateClass.newInstance(),sobjs);
					}else if(EasyPageController.TEMPLATE_TYPE_FREEMARKER.equalsIgnoreCase(EasyPageContext.threadLocalTemplateType.get())){
						log.info("The type of the template does not support.");
					}

				}else{
					// request attribute
					if(null != ma && ma.size() != 0){
						for(Map.Entry<String,Object> m:ma.entrySet()){
							easyPageContext.getRequest().setAttribute(m.getKey(),m.getValue());
						}
					}
					req.getRequestDispatcher("/" + pathName + easyPageContext.getPageSuffix()).forward(req,res);
				}
			}
		}catch(IOException e){
			e.printStackTrace();
		}catch(ServletException e){
			e.printStackTrace();
		}catch(IllegalArgumentException e){
			e.printStackTrace();
		}catch(IllegalAccessException e){
			e.printStackTrace();
		}catch(InvocationTargetException e){
			e.printStackTrace();
		}catch(InstantiationException e){
			e.printStackTrace();
		}

		return pathName;
	}
}
